<?php

namespace app\common\model;

use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'state_text',
        'pinned_text',
        'images_array',
        'share_money',

    ];

    public function getShareMoneyAttr($value, $data)
    {
        $money = bcmul($data['price'], bcdiv(config('site.share_earnings'), 100, 2), 2);
        return $money > 0 ? $money : 0;
    }
    public function getImageAttr($value, $data)
    {
        return $value ? cdnurl($value, true) : $value;
    }

    public function getImagesArrayAttr($value, $data)
    {
        if ($data['images']) {
            $array = explode(',', $data['images']);
            foreach ($array as &$v) {
                $v = cdnurl($v, true);
            }
            return $array;
        }
        return [];
    }

    public function review()
    {
        return $this->hasMany('app\common\model\order\Review', 'goods_id', 'id');
    }

    public function getStateList()
    {
        return ['1' => __('State 1'), '2' => __('State 2')];
    }

    public function getPinnedList()
    {
        return ['1' => __('Pinned 1'), '2' => __('Pinned 2')];
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPinnedTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pinned']) ? $data['pinned'] : '');
        $list = $this->getPinnedList();
        return isset($list[$value]) ? $list[$value] : '';
    }
}
